package com.zl.bcyappserver.service.asyn;

import com.zl.bcyappserver.service.asyn.picture.PictureMethodService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.CountDownLatch;

/**
 * Created by ZhongLeiDev at 2019/12/4
 */
@Service
@Slf4j
public class AsynPictureMethodServiceImpl {

    private PictureMethodService pictureMethodService;
    private int currentCount = 1;

    @Autowired
    public AsynPictureMethodServiceImpl(PictureMethodService pictureMethodService) {
        this.pictureMethodService = pictureMethodService;
        resetCurrentCount();
    }

    private int getCurrentCount() {
        return currentCount;
    }

    private void increaseCurrentCount() {
        currentCount ++;
    }

    private void resetCurrentCount() {
        currentCount = 1;
    }

    public void AsynGetTagDetails(String tagId, int maxCount) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(maxCount);
        pictureMethodService.login(tagId);
        for (;getCurrentCount()<=maxCount;) {
            log.info("Thread-"+ getCurrentCount() + "-Started!");
            pictureMethodService.asynGetBcyTagDetailPictures(tagId,getCurrentCount(), countDownLatch);
            increaseCurrentCount();
        }
        countDownLatch.await();
        resetCurrentCount();
    }

    public void AsynGetUserWorks(Set<String> uidSet) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(uidSet.size());
        for (String uid : uidSet) {
            log.info("UserWorksThread-"+ getCurrentCount() + "-Started!");
            pictureMethodService.asynGetUserWorkSet(uid, countDownLatch);
            increaseCurrentCount();
        }
        countDownLatch.await();
        resetCurrentCount();
    }

}
